package cn.kgc.web.service.impl;

import cn.kgc.web.entity.Emp;
import cn.kgc.web.mapper.EmpMapper;
import cn.kgc.web.service.EmpService;
import cn.kgc.web.utils.MybatisUtil;
import cn.kgc.web.utils.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.HashMap;
import java.util.List;

/**
 * @author: 课工场
 * @since 2023/9/27
 */
public class EmpServiceImpl implements EmpService {

    private EmpMapper empMapper = MybatisUtil.getMapper(EmpMapper.class);

    @Override
    public ResponseResult addEmp(Emp emp) {

        ResponseResult responseResult = new ResponseResult();

        //将emp信息 添加到数据库
        try {

            Integer line = empMapper.addEmp(emp);
            responseResult.setCode(200);
            responseResult.setMsg("添加成功");

        } catch (Exception e) {
            responseResult.setCode(500);
            responseResult.setMsg("添加失败");
        }

        return responseResult;
    }

    @Override
    public ResponseResult updateEmp(Emp emp) {

        ResponseResult responseResult = new ResponseResult();

        try {
            Integer line = empMapper.updateEmp(emp);
            responseResult.setMsg("更新成功").setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setMsg("更新失败").setCode(500);
        }

        return responseResult;
    }

    @Override
    public ResponseResult deleteById(Integer id) {

        ResponseResult responseResult = new ResponseResult();

        try {
            Integer line = empMapper.deleteById(id);
            responseResult.setCode(200).setMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            responseResult.setCode(500).setMsg("删除失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult empPage(Integer page, Integer limit, String ename) {

        ResponseResult responseResult = new ResponseResult();


        PageHelper.startPage(page,limit);

        List<Emp> emps =  empMapper.getList(ename);

        PageInfo<Emp> empPageInfo = new PageInfo<>(emps);
        long total = empPageInfo.getTotal();
        List<Emp> list = empPageInfo.getList();


        HashMap<String, Object> data = new HashMap<>();
        data.put("list",list);
        data.put("total",total);

        responseResult.setMsg("查询成功").setCode(200).setData(data);
        return responseResult;
    }
}
